let http = require('http')
let https = require('https') 

let url = require('url')
const cheerio = require('cheerio');
const server = http.createServer()

server.on('request', (req, res) => { 
    const url0bj = url.parse(req.url,true)
    res.writeHead(200,{
        //键值对
        //跨域
        "content-type":"application/json;charset=utf-8",
        "access-control-allow-origin":"*"//允许所有域访问

    })
    if(url0bj.pathname === '/api/getInfo'){
            //做和爬虫有关的事情
            //参数传到一个匿名异步函数，用来做爬虫
httpget(data =>  res.end(spider(data))

)
    }else{
        res.end('404')
    }
})
//https://i.maoyan.com/
function httpget(cb){
let data = '' 
https.get('https://i.maoyan.com/#movie',(res)=>{ 
    res.on('data', (chunk)=>{     
        data += chunk
})//不断监听data的内容，拿到chunk数据片段
res.on('end',()=>{
    //监听到最后处理完数据
    cb(data)
})
})  
}
function spider(data){
    const $ = cheerio.load(data);
    let $movieList = $('.column.content')
    let movies  =  []
    //jquery选择器  document

    $movieList.each((index,value)=>{
        movies.push({
            title:$(value).find('.title').text(),
            grade:$(value).find('.grade').text(),
            actor:$(value).find('.actor').text(),
            
        })
    })
    console.log(movies)
    return JSON.stringify(movies)
}

server.listen(80,()=> { 
    console.log('http://127.0.0.1')
})

